(function (window, $, Camera) {

    $(function () {
        // 设置iframe的高度，非精准适应屏幕高度
        var docHeight = $(document).height();
        $('#reportContainer, #applicationContainer').height(docHeight - 300);

        var cardModel = [
            {type: "1", name: "身份证"},
            {type: "2", name: "户口簿"},
            {type: "3", name: "护照"},
            {type: "4", name: "军官证"},
            {type: "5", name: "士兵证"},
            {type: "6", name: "港澳居民来往内地通行证"},
            {type: "7", name: "台湾同胞来往内地通行证"},
            {type: "8", name: "临时身份证"},
            {type: "9", name: "外国人居住证"},
            {type: "10", name: "警官证"},
            {type: "11", name: "香港身份证"},
            {type: "12", name: "澳门身份证"},
            {type: "13", name: "台湾身份证"},
            {type: "14", name: "其他证件"}
        ];
        var typesModel = [{type: 1, name: "个人简单版"},
            {type: 2, name: "个人明细版"},
            {type: 3, name: "股指期货版"}];

        var vm = avalon.define({
            $id: 'personInquiryPage',
            cardModel: cardModel,
            typesModel: typesModel,
            firstStepVo: {},
            reqReportVo:{},
            inquiryModel: {
                id: '',
                cardType: 1,
                cardNum: '',
                userName: '',
                format: 2,
                similar: 0,
                phone:'',
                cardImgUrl:'',
                sceneImgUrl:''
            },
            application: {
                content: ''
            },
            chargeVo: {
            	chargeNo: '',
            	isPayFee: 0
            },
            report: {
                content: ''
            },
            sencePic:[],
            cardPic: [],
            otherPic: [],
            idFrontPic:'',
            idBackPic:'',
            step: 1,
            queryCount : 0,
            errMsg: {},
            manualFaceVerify: false,
            showError: function (reasons) {
                var result = {};
                for (var i = 0; i < reasons.length; i++) {
                    var reason = reasons[i];
                    var element = reason.element;
                    var name = element.id;
                    if (name) {
                        result[name] = reason;
                    }
                }
                vm.errMsg = result;
            },
            isIdCard: function () {
                return vm.inquiryModel.cardType == 1;
            },
            uploadPhoto:function (imgList,callback,sourceType){
            	 console.log("uploadImgList:", imgList);
                var prefix = 'data:image/png;base64,'; // 注意图片格式
                var prefixJpeg = "data:image/jpeg;base64,";
                var vo={};
                if(sourceType==''||sourceType==null){
                    vo.sourceType=2;
                }else{
                    vo.sourceType=sourceType;
                }
                var targetList=[];
                if(imgList.length<1){
                    callback({});
                }else{
                    for(var i=0;i<imgList.length;i++){
                        targetList.push(imgList[i].path.replace(prefix,"").replace(prefixJpeg, ""));
                    }
                    console.log("targetList:", targetList);
                    vo.base64Files=targetList;
                    console.log("start:", "开始上传")
                    $.ajax({
                        url: 'file/upload/base64',
                        data: JSON.stringify(vo),
                        contentType: "application/json; charset=UTF-8",
                        type: "POST",
                        dataType:"json",
                        success: function (responseJSON) {
                            callback(responseJSON);
                        }
                    });
                }
                return true;
            },
            gotoStep: function (step) {
                if(step == 2){
                    var imgList=vm.cardPic.concat(vm.otherPic);
                    vm.uploadPhoto(imgList,this.uploadCallback,2);
                    return;
                }
                
                if(step==3 && vm.isIdCard() && !vm.manualFaceVerify){
                    if(!confirm("人脸识别未通过,确定进入下一步吗？")){
                        return;
                    }
                }
                if(step == 4){
                	//hw.finalize();
                }
                if(step == 3){
                	
                	$("#faceLeft").html("");
                	console.log("faceLeft:", "清空faceLeft内容");
                }
                vm.step=step;
            },
            verifyFace: function () {
                // 应该还有自动人脸识别
                if (vm.manualFaceVerify) {
                    vm.gotoStep(3);
                } else {
                    alert('请进行人脸识别审核');
                }
            },
            
            signHanlder: function (type) {
                // 签名控制
            	if(type == 1){//切换到签名屏
            		document.getElementById("rightDiv").scrollTop = document.body.scrollHeight;
            		hw.switchSignMonitor();
            		$("#PCMonitorLabel").css("display","");
            		$("#signMonitorLabel").css("display","none");      		
            		$("#pcDiv").css("display","none");
            		$("#menuListDiv").css("display","none");
            		
            		return ;
            	}
            	
            	if(type == 2){//切换到PC
            		
            		hw.switchPCMonitor();
            		
            		$("#PCMonitorLabel").css("display","none");
            		$("#signMonitorLabel").css("display","");
            		$("#menuListDiv").css("display","");
            		$("#pcDiv").css("display","");
            		
            		var base64Sign = hw.base64Img();  
            		console.log('base64Sign:', base64Sign);
            		if(base64Sign != undefined && base64Sign != ""){
            		
	            		$('#applicationContainer')[0].contentDocument.getElementById("userNameImg").style.display="";
	            		$('#applicationContainer')[0].contentDocument.getElementById("userNameImg").src = "data:image/png;base64," + base64Sign;
            	    }
            		
            		return ;
            	}
            	
            },
            
            phoneHanlder : function(type){
            	// 签名控制
            	if(type == 1){//切换到签名屏
            		
            		$("#phone").focus();
            		$('#ca')[0].contentDocument.getElementById("view1").style.display="none";
            		$("#cameraDiv").css("display","none");
            		$("#menuListDiv").css("display","none");
            		$('.auth_keybord').scrollTop = document.body.scrollHeight;
            		hw.switchSignMonitor();     		
            		return ;
            	}

            },
            
            uploadCallback:function(res){

                if(res.code==='SUCCESS'){
                    var picStr='';
                    for(var i=0;i<res.data.length;i++){
                        picStr+=res.data[i].id+";";
                       vm.cardPic[i].id=res.data[i].id;       
                    }
                    vm.inquiryModel.cardImgUrl=picStr;
                    console.log('vm.inquiryModel.cardImgUrl:', vm.inquiryModel.cardImgUrl);
                    console.log('vm.isIdCard():', vm.isIdCard());
                    var facRectFlag = true;
                    console.log('uploadCallback idFrontPic:', vm.idFrontPic);
                    if(vm.isIdCard() && vm.idFrontPic != ''){
                    	$("#faceSimilarDiv").show();
                    	$("#similarDiv").show();
                    	$("#scanDiv").hide();
                    } else {
                    	vm.manualFaceVerify = true;
                    	facRectFlag = false;
                    	$("#faceSimilarDiv").hide();
                    	$("#similarDiv").hide();
                    	$("#scanDiv").show();
                    	
                    }
                    vm.step=2;
                    Camera.destroy();
                    Camera.init({
                        container: '#faceLeft',
                        id: 'ca',
                        width:280,
                        height:200,
                        viewWidth:240,
                        viewHeight:180,
                        device:"resources/js/camera/device.html",
                        type:2,
                        facRect:facRectFlag
                    });
                    
                } else {
                	
                	if(res.code == 'SID_CHECK_FAIL'){
							location.href = res.data;
							return;
					}
                    alert("文件上传失败");
                }
            },
            readIdCard: function () {
                var idCardData = Camera.readIdCardData();
                vm.inquiryModel.userName = idCardData.name;
                vm.inquiryModel.cardNum = idCardData.id;
                vm.idFrontPic = idCardData.front;
                vm.idBackPic = idCardData.back;
                vm.cardPic.push({id:"",path: vm.idFrontPic});
                vm.cardPic.push({id:"",path: vm.idBackPic});
                Camera.stopIdCard();
            },
            changeIdType: function(){
                vm.inquiryModel.cardType=$("#idType").val();
            },
            readIdCardImg:function (index) {
                return Camera.readIdCardImg(index);
            },
            compare:function(){
            	
            	var similar = Camera.VerifyFaceDetect();
            	vm.similar = similar;
            	if(undefined == faceRatio){
            		faceRatio = 70;
            	}
            	console.log('faceRatio:', faceRatio);
            	
            	if(similar >= faceRatio){
            		$("#similarDiv").html(similar + "%");
            		vm.manualFaceVerify = true;
            	} else {
            		
            		$("#similarDiv").html("<font color='red'>" + similar + "%<font>");
            	}
            	
            	vm.senceScan();
            },
            
            senceScan : function(){
            	
            	var img = Camera.scan(1);
            	console.log('faceimg:', img);
            	if(! vm.isIdCard() || (vm.isIdCard() && vm.idFrontPic == '')){
        			vm.idFrontPic = img;
        			console.log('idFrontPic:', img);
        		}
            	var imgList = [];
            	vm.sencePic.push({id:'',path: img});
            	var imgList = vm.sencePic;
            	vm.uploadPhoto(imgList, function(res){
            		console.log('res:', res);
            		vm.sencePic[0].id = res.data[0].id;
            		vm.inquiryModel.sceneImgUrl = res.data[0].id;
            		
            	}, 2);
            },
            
            scan: function (imgType, deviceType) {
                var img = Camera.scan(deviceType);
                if (imgType == 2) {
                    vm.otherPic.push({id:'',path: img});
                } else {
                    vm.cardPic.push({id:'',path: img});
                }
                //             if (type == 2) {
                //                 vm.otherPic.push(item);
                //             } else {
                //                 vm.cardPic.push(item);
                //             }
                $('<img/>').attr('src', img).appendTo(document.body);
            },

            charge: function (type) {

            	if(type == 1){
                	if(vm.firstStepVo.isFee == 0 ||  vm.chargeVo.isPayFee == 1){
                		console.log("缴费：","不需交费或已缴费，不提交后台，非正常操作");
                		return ;
                	}
                }
            	
            	if(type == -1 && vm.chargeVo.isPayFee == 0){
            		console.log("撤销缴费：","不需缴费或未缴费，不提交后台，非正常操作");
            		return ;
            	}
            	            	
                //user=%E8%AE%B8%E5%BA%86%E8%BE%89&ctype=0&idno=440111199302210335&querytype=21
                //&reltel=&relname=&relcerttype=&relcertno=&forwardtype=1
                
                var url = "inquiry/charge";
                var msg = "请确认此人已经缴费，再进行此操作！";
                var tip = "查询缴费";
                
                var data = {};
                if(type == 1){
                	
                	data.user=vm.inquiryModel.userName;
                    data.ctype = vm.inquiryModel.cardType;
                    data.idno = vm.inquiryModel.cardNum;
                	data.id= vm.inquiryModel.id;
                    data.querytype = vm.firstStepVo.querytype;
                	data.forwardtype = 1;
                }
                
                if(type == -1){
                	
                	//{chargeNO:"+ chargeNo +",updatetype:\"2\",forwardtype:\"2\"}
                	data.id= vm.inquiryModel.id;
                	data.chargeNo = vm.chargeVo.chargeNo;
                	data.updatetype = 2;
                	data.forwardtype = 2;
                	url = "inquiry/charge/cancel";
                	msg =  "确定要撤销此人的已缴费信息吗？";
                	tip = "撤销缴费";
                }
                
                layer.confirm(msg, {
      			  btn: ['取消','确定'] //按钮
      			}, function(){
      				layer.msg('已取消', {time: 1000 });
      			}, function(){
      				$.ajax({
      					type : "post", // 提交方式
      					url : url,// 路径
      					data : data,// 数据，这里使用的是Json格式进行传输
      					dataType:"json",
      					success : function(result) {// 返回数据根据结果进行相应的处理
      						
      						if (result.code == "SUCCESS") {
      							
      							if(type == 1){
      								
      								vm.chargeVo.chargeNo = result.data.chargeNo;
      								vm.chargeVo.isPayFee = 1;
      								$("#cancelChargeBtn").removeClass("grey");
      								$("#chargeBtn").addClass("grey");
      							}
      							
      							if(type == -1){
      								
      								$("#chargeBtn").removeClass("grey");
      								$("#cancelChargeBtn").addClass("grey");
      								vm.chargeVo.isPayFee = 0;
      								vm.chargeVo.chargeNo = '';
      							}
      							alert(tip + "成功");
      						
      						} else {
      							if(result.code == 'SID_CHECK_FAIL'){
          							location.href = result.data;
          							return;
          						}
      							alert(tip + "失败");
      							return;
      						}
      					}
      				});
      			});
                
                // if (vm.step >= 3) {
                //     vm.submit();
                // }

            },
            //到收费界面
            inquiryToPayment: function () {
                var data = vm.inquiryModel.$model;
                $.ajax({
                    url: 'inquiry/save',
                    type: 'post',
                    data: data,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {
                            vm.gotoStep(4);
                            vm.firstStepVo = resp.data.firstStepVo;
                            vm.inquiryModel.id = resp.data.id;
                        } else {
                        	if(resp.code == 'SID_CHECK_FAIL'){
      							location.href = resp.data;
      							return;
      						}
                        	layer.msg(resp.msg == "" ? "查询失败" : resp.msg);
                        }
                    }
                });
            },
            //到申请表界面
            inquiryToApplyTbl: function () {
            	
            	if(vm.firstStepVo.isFee == 1 &&  vm.chargeVo.isPayFee == 0){
            		
            		console.log("缴费：","该用户需要交费，请收费成功后在点击下一步操作");
            		
            		layer.msg('本次查询需要缴费，请点击确认缴费按钮', {time: 2000 });
            		
            		return ;
            	}
            	
                var firstStepVo = vm.firstStepVo;
                var data = {};
                data.querylog = firstStepVo.queryLog;
                data.queryreason = '04';
                data.chargestathidden = firstStepVo.chargeStat;
                data.querytypehidden = firstStepVo.querytype;
                data.querynumber = firstStepVo.queryNum;
                data.historychargestat = firstStepVo.historyChargeStat;
                data.name=vm.inquiryModel.userName;
                data.certtype = vm.inquiryModel.cardType;
                data.certno = vm.inquiryModel.cardNum;
                data.id= vm.inquiryModel.id;
                data.querytype = firstStepVo.querytype;
                data.reltel = vm.inquiryModel.phone;
                if(vm.chargeVo.chargeNo != ''){
                	data.chargeNOHidden = vm.chargeVo.chargeNo;
                }
                
                signIframe.initCreateContainer("userNameSignTd", "userNameSignIframe", 350, 120)
                
                //$("#personStep5").load("inquiry/person/step5");
                //querylog=yes&
                //queryreason=04&chargeNOHidden=&dissentid=&chargestathidden=&querytypehidden=24&querynumber=1&historychargestat=0
                //&name=%C1%F5%D0%CB%C3%DC&certtype=0&certno=412822198212021417&reltel=&relname=&relcerttype=&relcertno=&querytype=24
                $.ajax({
                    url: 'inquiry/apply/table',
                    type: 'post',
                    data: data,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {

                            vm.reqReportVo = resp.data;
                            vm.reqReportVo.html = "";
                            
                            vm.gotoStep(5);
                           
                            var html = resp.data.html;
                            vm.application.content = html;
                            
                            var ifrDoc = $('#applicationContainer')[0].contentDocument;
                            
                            ifrDoc.body.innerHTML = html;
                            ifrDoc.body.style.cssText = 'background-color: #ffffff;';
//                            if(vm.inquiryModel.phone != null){
//                            	$('#applicationContainer')[0].contentDocument.getElementById("userphone").innerHTML= vm.inquiryModel.phone;
//                            }
                          
                            $('#applicationContainer').css("height", 500);
                            //inquiryUtil.appendSignScript(ifrDoc);
                                                       
                        } else {
                        	if(resp.code == 'SID_CHECK_FAIL'){
      							location.href = resp.data;
      							return;
      						}
                        	layer.msg(resp.msg == "" ? "查询失败" : resp.msg);
                        }
                    }
                });
            },
            printApplyTbl: function () {
                // window.print();
                // 这里需要弹框出来提示 完成 / 重新打印
                window.commonPrint('applicationContainer');
                // $('#applicationContainer')[0].contentWindow.print();
            },
            
            inquiryCreditReport: function () {
            	
            	inquiryUtil.saveSign(vm.inquiryModel.id, hw.base64Img());            	             	 
           	    //hw.finalize();
            	vm.queryCount ++;
            	$("#personQueryRed").hide();
                $("#personQueryGrey").show();
                
                //branchquery/dissentInnerQueryActionV2.do?name=������&certtype=0&certno=412822198212021417&vertype=24
                //&dissentid=201706024401240400050_c5d7b54d717ec68e0e466fbc7a7adffb&queryreason=04&chargeNO=G2017060200000105705131
                var data = vm.reqReportVo.$model;
                data.name = vm.inquiryModel.userName;
                data.certno = vm.inquiryModel.cardNum;
                data.id= vm.inquiryModel.id;
                data.queryreason = "04";
                data.certtype = vm.inquiryModel.cardType;
                if(vm.chargeVo.chargeNo != ''){
                	data.chargeNO = vm.chargeVo.chargeNo;
                }
                $.ajax({
                    url: 'inquiry/credit/report',
                    type: 'post',
                    data: data,
                    dataType:"json",
                    success: function (resp) {
                        if (resp.code === 'SUCCESS') {
                            vm.gotoStep(6);
                            // vm.report.content = resp.data.html;
                            $('#reportContainer')[0].contentDocument.body.innerHTML = resp.data.html;
                            $('#reportContainer')[0].contentDocument.body.style.cssText = 'background-image:url(resources/images/pbccrc_watermark.gif);background-repeat:repeat;background-color: #ffffff;';
                            forbidLeftAndTop.forbid();
                        } else {
                        	
                        	if(resp.code == 'SID_CHECK_FAIL'){
      							location.href = resp.data;
      							return;
      						}
                        	
                        	var errorMsg = (resp.msg == "" ? "查询失败" : resp.msg) + "，请等待5秒后重新查询";
                        	if(vm.queryCount == 3){
                        		errorMsg = (resp.msg == "" ? "查询失败" : resp.msg) + "，查询失败次数过多，请使用原系统查询征信";
                        	}
                        	layer.msg(errorMsg);                        	
                        }
                    }
                });
                
                if(vm.queryCount > 3){
                	return ;
                }
                window.setTimeout(function () {
                 	$("#personQueryRed").show();
                     $("#personQueryGrey").hide();
                }, 5000);           
            },
            printReport: function () {
                // window.print();
                // 这里需要弹框出来提示 完成 / 重新打印
                if (confirm("你确定要打印该报告吗？")) {
                    var data = {};

                    data.id = vm.inquiryModel.id;
                    data.printResult = 1;
                    $.ajax({
                        url: 'inquiry/credit/print',
                        type: 'post',
                        data: data,
                        dataType:"json",
                        success: function (resp) {
                            if (resp.code === 'SUCCESS') {
                                
                                // $('#reportContainer')[0].contentWindow.print();
                            }
                        }
                    });
                    window.commonPrint('reportContainer');
                } else {
                    //alert("点击了取消");
                }


            },
            cancelPrintReport: function (flag) {
            	//打印结果(0：未打印，-1-取消打印， 1-成功，2-失败)
            	var printResult = -1;
            	var msg = "你确定要取消打印吗？";
            	if(flag == 2){
            		msg = "你确定打印完成并返回吗？";
            		printResult = 1;
            	}
            	if(flag == 3){
            		msg = "你确定打印失败并返回吗？";
            		printResult = 2;
            	}
                if (confirm(msg)) {
                	if(printResult != 1){
                		var data = {};

                        data.id = vm.inquiryModel.id;
                        data.printResult = printResult;
                        $.ajax({
                             url: 'inquiry/credit/print',
                             type: 'post',
                             data: data,
                             dataType:"json",
                             success: function (resp) {

                             }
                        });
                	}
                	
                    forbidLeftAndTop.cancel();
                    // 跳转到初始界面
                    location.href="index?sid=" + sid + "&showMenu=PERSON_QUERY_A";
                    //$("#BUS_QUERY").click();$("#PERSON_QUERY_A").click();
                    // vm.gotoStep(1);
                }

            },
            submit: function () {
                // 提交数据并跳转到第四步
                var card = vm.inquiryModel.cardType;
            },
            // scan: function (type) {
            //     Camera.scan2Upload({sourceType: type}).then(function (resp) {
            //         if (resp.code === 'SUCCESS') {
            //             var id = resp.data.id;
            //             var path = 'file/download?sid=' + getSid() + '&id=' + id;
            //             var item = {
            //                 // type: type,
            //                 path: path
            //             };
            //             if (type == 2) {
            //                 vm.otherPic.push(item);
            //             } else {
            //                 vm.cardPic.push(item);
            //             }
            //         }
            //     });
            //
            // },
            removePic: function (index, type) {
                if (type == 2) {
                    vm.otherPic.splice(index, 1);
                } else {
                    vm.cardPic.splice(index, 1);
                }
            },
            validate: {
                onManual: $.noop,
                onValidateAll: function(reasons){
                	console.log('reasons:', reasons);
                    vm.showError(reasons);
                    if (!reasons.length) {
                    	
                    	console.log('validate idFrontPic:', vm.idFrontPic);
                        if (vm.isIdCard() && vm.idFrontPic != '') {
                        	$("#faceSimilarDiv").show();
                        	$("#similarDiv").show();
                        	$("#scanDiv").hide();
                        } else {
                        	vm.manualFaceVerify = true;
                        	$("#faceSimilarDiv").hide();
                        	$("#similarDiv").hide();
                        	$("#scanDiv").show();
                           
                        }
                        vm.gotoStep(2);
                    }
                },

                onError: function (reasons, ev) {
                    vm.showError(reasons);
                },
                onSuccess: function (reasons, ev) {
                    vm.errMsg = '';
                },
                // onComplete: avalon.noop,//针对单个表单元素
                // onReset: avalon.noop, //针对单个表单元素
                // validateInBlur: true, // {Boolean} true，在blur事件中进行验证,触发onSuccess, onError, onComplete回调
                // validateInKeyup: true, // {Boolean} true，在keyup事件中进行验证,触发onSuccess, onError, onComplete回调
                validateAllInSubmit: false // {Boolean} true，在submit事件中执行onValidateAll回调
                // resetInFocus: true, // {Boolean} true，在focus事件中执行onReset回调,
                // deduplicateInValidateAll: false // {Boolean} false，在validateAll回调中对reason数组根据元素节点进行去重
            }
        });
        avalon.scan($("#page-content-wrapper")[0]);
        window.setTimeout(function () {
            var cameraType = 4; // 资料拍摄
            if (vm.isIdCard()) {
                cameraType = 5;
            }
            Camera.destroy();
            Camera.init({
                container: '#videoContainer',
                id: 'ca',
                width:500,
                height:420,
                viewWidth:500,
                viewHeight:375,
                type: cameraType,
                facRect:true
            });

        }, 1000);

    });

}(window, jQuery, Camera));